package com.mdata.model.vo;

import com.mdata.model.dto.wechat.result.Department;
import com.mdata.model.dto.wechat.result.UserList;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Data
public class DepartmentSimpleVO {

    private Integer id;

    private String name;

    private Integer parentId;

    private List<DepartmentSimpleVO> childrens;

    private List<UserList> simpleList;

    /**
     * 部门人数
     */
    private Integer simpleCount;

    /**
     * 部门群数
     */
    private Integer groupChatCount;

    public static DepartmentSimpleVO fromDepartment(Department department, Map<String, Integer> simpleGroupChatCountMap){
        DepartmentSimpleVO departmentTreeVO = new DepartmentSimpleVO();
        BeanUtils.copyProperties(department, departmentTreeVO);

        List<DepartmentSimpleVO> departmentSimpleVOS = fromDepartmentList(department.getChildrens(), simpleGroupChatCountMap);
        departmentTreeVO.setChildrens(departmentSimpleVOS);

        // 合计部门人数，子部门人数也要算到父部门中
        List<UserList> simpleList = department.getSimpleList();
        Integer myDepartmentSimpleCount = simpleList.size();
        Integer sonDepartmentSimpleCount = Optional.ofNullable(departmentSimpleVOS).map(o -> o.stream().mapToInt(b -> b.getSimpleCount()).sum()).orElse(0);
        departmentTreeVO.setSimpleCount(myDepartmentSimpleCount + sonDepartmentSimpleCount);

        // 合计部门群数，子部门群数也要算到父部门中
        Integer myDepartmentGroupChatCount = simpleList.stream().mapToInt(departmentSimple -> Optional.ofNullable(simpleGroupChatCountMap.get(departmentSimple.getUserId())).orElse(0)).sum();
        Integer sonDepartmentGroupChatCount = Optional.ofNullable(departmentSimpleVOS).map(o -> o.stream().mapToInt(b -> b.getGroupChatCount()).sum()).orElse(0);
        departmentTreeVO.setGroupChatCount(myDepartmentGroupChatCount + sonDepartmentGroupChatCount);
        return departmentTreeVO;
    }

    public static List<DepartmentSimpleVO> fromDepartmentList(List<Department> departmentList, Map<String, Integer> simpleGroupChatCountMap){
        if(CollectionUtils.isEmpty(departmentList)){
            return null;
        }
        return  departmentList.stream().map(o -> fromDepartment(o, simpleGroupChatCountMap)).collect(Collectors.toList());
    }

    @Override
    public String toString() {
        return "DepartmentSimpleVO{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", parentId=" + parentId +
                ", childrens=" + childrens +
                ", simpleList=" + simpleList +
                ", simpleCount=" + simpleCount +
                ", groupChatCount=" + groupChatCount +
                '}';
    }
}
